package top.gbiot.mq;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.gbiot.common.AppConstant;
import top.gbiot.common.domain.DataMap;
import top.gbiot.common.utils.StringUtils;
import top.gbiot.data.domain.IotData;
import top.gbiot.data.mapper.IotDataMapper;
import top.gbiot.device.domain.IotDevice;
import top.gbiot.device.mapper.IotDeviceMapper;
import top.gbiot.redis.util.RedisUtils;
import top.gbiot.config.mqtt.MqttPushClient;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 消息队列消费者类，主要接收消息队列转发过来的设备数据
 */
@Service
public class MessageConsumerService {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IotDeviceMapper iotDeviceMapper;
    @Autowired
    private IotDataMapper iotDataMapper;

    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    @Transactional(rollbackFor = Exception.class)
    @JmsListener(destination =AppConstant.MQ_QUEUE_NAME)
    public void receiveMessage(String payload) {    // 进行消息接收处理
        logger.info("消息队列MQ接收消息内容 : " + payload);
        if(StringUtils.isBlank(payload)){
            return;
        }
        //1.解析设备数据
        DataMap dataMap = new DataMap();
        try {
             dataMap = JSON.parseObject(payload,DataMap.class);
        }catch (Exception e){
            logger.warn("json数据解析错误，请检查硬件数据格式是否正确！ 数据报文："+payload);
        }

        //logger.info("json解析后的设备消息内容 : " +dataMap);

        //2.从Redis中获取设备数据并解析
        String deviceCacheJson=redisUtils.get1("deviceCache");
        if(StringUtils.isBlank(deviceCacheJson)){
            return;
        }
        //logger.info("json解析 后的Redis设备内容 : " +deciveCacheJson);
        deviceCacheJson = deviceCacheJson.substring(1, deviceCacheJson.length() - 1);
        //去除转义符
        deviceCacheJson = deviceCacheJson.replaceAll("\\\\", "");

        //json数据转换
        List<DataMap> deciveCacheMapLits = new ArrayList<>();
        try {
             deciveCacheMapLits=JSON.parseArray(deviceCacheJson,DataMap.class);
        }catch (Exception e){
            logger.warn("json数据解析缓存数据错误，请检查缓存数据格式是否正确！");
        }
        if(deciveCacheMapLits.size()>0){
            //1.获取设备sn码，并校验缓存中是否存在与之对应的设备，没有则不新增设备数据
            String dataSn=dataMap.getStr("sn");
            String cacheSn="";
            String cacheDeviceId="";
            if(StringUtils.isNotBlank(dataSn)){
                for (DataMap dataCache:deciveCacheMapLits) {
                    if(dataCache.containsValue(dataSn)){
                        cacheSn=dataCache.getStr("device_sn");
                        cacheDeviceId=dataCache.getStr("device_id");
                        break;
                    }
                }
            }
            //2.根据获取的device_id获取设备信息
            IotDevice iotDevice =iotDeviceMapper.selectIotDeviceById(cacheDeviceId);
            //3.新增数据
            if(iotDevice!=null){
                IotData iotData = new IotData();
                iotData.setDataId(UUID.randomUUID().toString().replaceAll("-",""));
                iotData.setDeviceId(iotDevice.getDeviceId());
                iotData.setDeviceSn(iotDevice.getDeviceSn());
                iotData.setDeviceName(iotDevice.getDeviceName());
                iotData.setDeviceType(iotDevice.getDeviceType());
                iotData.setData(dataMap.getStr("data"));
                iotData.setDataUnitName(dataMap.getStr("unit"));
                iotData.setDataType(dataMap.getStr("type"));
                iotData.setCreateDate(new Date());
                iotDataMapper.insertIotData(iotData);
                logger.info("新增数据成功" );
            }
        }
    }
}
